//Given a collection of numbers, nums, that might contain duplicates, return all
// possible unique permutations in any order. 
//
// 
// Example 1: 
//
// 
//Input: nums = [1,1,2]
//Output:
//[[1,1,2],
// [1,2,1],
// [2,1,1]]
// 
//
// Example 2: 
//
// 
//Input: nums = [1,2,3]
//Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
// 
//
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 8 
// -10 <= nums[i] <= 10 
// 
// Related Topics 回溯算法 
// 👍 701 👎 0


package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Java：Permutations II
class P47PermutationsIi {
    public static void main(String[] args) {
        P47PermutationsIi.Solution solution = new P47PermutationsIi().new Solution();
        System.out.println(solution.permuteUnique(new int[]{1, 1, 3}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] visited;

        public List<List<Integer>> permuteUnique(int[] nums) {
            visited = new boolean[nums.length];
            Arrays.sort(nums);
            permute(nums, 0, new ArrayList<>());
            return result;
        }

        private void permute(int[] nums, int begin, ArrayList<Integer> list) {
            if (list.size() == nums.length) {
                result.add(new ArrayList<>(list));
                return;
            }
            for (int i = 0; i < nums.length; i++) {
                if (visited[i] == false) {
                    if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1]) {
                        continue;
                    }
                    list.add(nums[i]);
                    visited[i] = true;
                    permute(nums, begin + 1, list);
                    list.remove(list.size() - 1);
                    visited[i] = false;

                }

            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}